from app.Pojo.AdminUser import AdminUser
from app.Mapper.AdminMapper  import AdminMapper
from app.Utils.exceptions import BusinessException
from datetime import datetime
import hashlib


class AdminService:
    def __init__(self, db):
        self.mapper = AdminMapper(db)

    def login(self, phone, password):
        """管理员登录"""
        # 查询管理员
        admin = self.mapper.get_by_phone(phone)
        # 检查管理员是否存在
        if not admin:
            raise BusinessException(400, "手机号或密码错误")
        # 检查密码是否正确（实际项目中应使用加密比较）
        if admin.password != self._encrypt_password(password):
            raise BusinessException(400, "手机号或密码错误")

        # 更新登录时间
        admin.update_time = datetime.utcnow()
        self.mapper.update(admin)

        # 返回用户信息
        return {
            "id": admin.id,
            "phone": admin.phone,
            "name": admin.name,
            "postion": admin.postion
        }
    def get_user(self, id):
        """获取用户信息"""
        admin = self.mapper.get_by_id(id)
        if not admin:
            raise BusinessException(400, "用户不存在")
        return {
            "gender":admin.gender,
            "email":admin.email,
            "image":admin.image,
            "password": admin.password,
            "age":admin.age,
            "phone": admin.phone,
            "name": admin.name,
            "postion": admin.postion,
            'createTime':admin.create_time,
            'updateTime':admin.update_time
        }
    def update_user(self, id, data):
        """更新用户信息"""
        admin = self.mapper.get_by_id(id)
        if not admin:
            raise BusinessException(400, "用户不存在")
        for key, value in data.items():
            setattr(admin, key, value)
            self.mapper.update(admin)
            admin.update_time = datetime.utcnow()

        return {
            "gender":admin.gender,
            "email":admin.email,
            "image":admin.image,
            "age":admin.age,
            "phone": admin.phone,
            "name": admin.name,
            "password": admin.password,
            "postion": admin.postion
        }

    def update_password(self, id):
        """更新用户密码"""
        admin = self.mapper.get_by_id(id)
        if not admin:
            raise BusinessException(400, "用户不存在")
        admin.password = self._encrypt_password(admin.password)
        self.mapper.update(admin)
        return {}


    def _encrypt_password(self, password):
        """密码加密处理"""
        # return hashlib.md5(password.encode('utf-8')).hexdigest()
        return password